package com.common.utils;

import java.lang.reflect.Method;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
//import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.aop.AfterReturningAdvice;

import com.system.domain.T_operation_log;
import com.system.mapper.T_operation_logMapper;

public class LogAfter implements AfterReturningAdvice {

	private static final Logger logger = Logger.getLogger(LogBefore.class);
	@Resource
	private T_operation_logMapper mapper;

	public void afterReturning(Object returnObj, Method method, Object[] args,
			Object target){
		//throws Throwable {

		try{
			String username = "";
			StringBuffer sb = new StringBuffer();
			for (int i=0; i<args.length;i++) {
				sb.append(i + "=" + args[i].toString()+ "; ");
				if (null == args[i]) {
					continue;
				}
				if (args[i] instanceof HttpServletRequest) {
					HttpServletRequest request = (HttpServletRequest) args[i];
					username = (String) request.getSession().getAttribute("FREE_CURRENT_USER");
				}
			}
			if (null == username||"".equals(username)) {
				logger.error("------操作日志&&&&&&方法执行后Start：-》用户未登录或者直接跳转（请求方法中没传递httprequest），获取不到用户session操作信息------");
				username= "用户未登录或者直接跳转";
			} else {
				logger.error("------操作日志&&&&&&方法执行后Start：-》获取到当前操作用户信息:" +username+"------");
			}
			logger.error("------操作日志&&&&&&方法执行后：-》获取到当前操作用户操作返回对象:" + returnObj.toString()+"------");
			logger.error("------操作日志&&&&&&方法执行后End：-》获取到当前操作用户操作返回类名字:" + target.getClass().getName() + " 方法:" + method.getName()+"------");

			//记录跟踪审计信息
			T_operation_log operlog = new T_operation_log();
			operlog.setUserid(username);
			operlog.setUrl("访问类名："+target.getClass().getName()+",方法名:"+method.getName());
			String retval = returnObj.toString();
			//返回的字符串如果超过utf-8编码格式字符串长度超过1333，数据库字段长度为4000，需要截取，否则报错；
			if(retval!=null&&retval.length()>1333){
				retval = retval.substring(0, 1333);
			}
			operlog.setRetvalue(retval);
			operlog.setOperation_end_tm(DateUtil.getCurrDateTime());
			operlog.setSession_id(Thread.currentThread().getId()+"");
			operlog.setSystemid("SH");
			//查询访问T_operation_log时，不做日志数据库记录，只做日志文件记录
			if(!target.getClass().getName().contains("T_operation_log")){
				mapper.save(operlog);
			}
		}catch(Exception e){
			e.printStackTrace();
			logger.error(e);
		}
	}
}
